package com.wocai.jrt.admin.common.service.impl;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.vteba.security.filter.DefaultUserAuthenticationToken;
import com.vteba.security.spi.JsonBean;
import com.vteba.security.spi.UserDetailsService;
import com.vteba.security.spi.cache.SecurityUserCache;
import com.vteba.security.user.IUserDetails;
import com.wocai.jrt.admin.user.model.ModuleMenu;
import com.wocai.jrt.admin.user.service.spi.ModuleMenuService;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;

/**
 * 根据机构加载不同的用户
 * @author yinlei
 * @date 2015年8月7日 下午12:53:54
 */
@Named
public class SaasUserDetailsServiceImpl implements UserDetailsService {
	private static final Logger LOGGER = LoggerFactory.getLogger(SaasUserDetailsServiceImpl.class);
	
	@Inject
	private EmployeeService employeeServiceImpl;
	
	@Inject
	private ModuleMenuService moduleMenuServiceImpl;
	
	@Inject
	private SecurityUserCache redisSpringSecurityUserCache;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		LOGGER.warn("this method is deprecated.");
		return null;
	}

	@Override
	public IUserDetails loadUser(String account, DefaultUserAuthenticationToken token) {
		String tenantCode = token.getOrgCode();
//		IUserDetails userDetails = (IUserDetails) redisSpringSecurityUserCache.getUserFromCache(account, tenantCode);
//		if (userDetails == null) {
//			LOGGER.info("cannot find User from cache, will load from Database, userName=[{}]", account);
//			// 获得用户
//			Employee employee = new Employee();
//			employee.setAccount(account);
//			employee.setOrgCode(tenantCode);
//			employee = employeeServiceImpl.unique(employee);
//			
//			if (employee != null) {
//				checkCase(employee, account, token.getOrgCode());
//				List<ModuleMenu> moduleMenuList = moduleMenuServiceImpl.getModuleMenuList(employee);
//				employee.setModuleMenuList(moduleMenuList);
//				userDetails = employee;
//				LOGGER.info("success find User from Database, userName=[{}], will put into redis.", account);
//				
//				redisSpringSecurityUserCache.putUserInCache(employee);
//			} else {
//				LOGGER.error("cannot find User from Database, userName=[{}]", account);
//				throw new UsernameNotFoundException("userName=[" + account + "], user cannot exist.");
//			}
//		} else {
//			LOGGER.info("success loaded User from cache, userName=[{}]", account);
//		}
		Employee employee = new Employee();
		employee.setAccount(account);
		employee.setOrgCode(tenantCode);
		employee.setState(1);
		employee = employeeServiceImpl.unique(employee);
		
		if (employee != null) {
			checkCase(employee, account, token.getOrgCode());
			List<ModuleMenu> moduleMenuList = moduleMenuServiceImpl.getModuleMenuList(employee);
			employee.setModuleMenuList(moduleMenuList);
//			userDetails = employee;
			LOGGER.info("success find User from Database, userName=[{}], will put into redis.", account);
			
			redisSpringSecurityUserCache.putUserInCache(employee);
		} else {
			LOGGER.error("cannot find User from Database, userName=[{}]", account);
			throw new UsernameNotFoundException("userName=[" + account + "], user cannot exist.");
		}
		return employee;
	}

	/**
	 * 检查区分大小写，因为mysql对varchar类型，默认不区分大小写<br>
	 * 改成二进制可以，但是没有确认过是否对index等有影响，这里<br>
	 * 暂时先这么判断。
	 * @param user 从数据库中查询到的用户信息
	 * @param userName 前端传来的数据，账号
	 * @param tenantId 租户代码（orgCode暂未使用）
	 */
	private void checkCase(IUserDetails user, String userName, String tenantId) {
		if (!userName.equals(user.getAccount())) {
			throw new UsernameNotFoundException("userName=[" + userName + "], user account case not matche.");
		}
	}
	
	@Override
	public List<GrantedAuthority> buildGranted(IUserDetails user) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public  JsonBean checkSerialNum(String orgCode) {
		/**
		 * expiredTime 和 员工数
		 */
		JsonBean json = new JsonBean();
		json.setCode(1);
		/*try{
			String timeAndNumber = KeyUtils.decrypt(PropUtils.get("serialno"), PropUtils.get("PCID"), KeyUtils.getKey(KeyUtils.PRIVATE_KEY_FILE));
			if(StringUtils.isBlank(timeAndNumber)){
				json.setCode(0);
				json.setMessage("硬件码错误");
				return json;
			}else if(StringUtils.isNotBlank(timeAndNumber.split("@")[0])){
				//判断到期日
				Date date = new Date();
				String str = timeAndNumber.split("@")[0];
				SimpleDateFormat spf=new SimpleDateFormat("yyyyMMddHHmmss");
				Date expiredTime = spf.parse(str);
				if(date.after(expiredTime)){
					json.setCode(0);
					json.setMessage("注册码已到期");
					return json;
				}
			}else if(StringUtils.isNotBlank(timeAndNumber.split("@")[1])){
				//有效员工数
				Employee params = new Employee();
				params.setState(1);
				if(employeeServiceImpl.countBy(params)>Integer.valueOf(timeAndNumber.split("@")[1])){
					json.setCode(0);
					json.setMessage("员工数量超过申请人数");
					return json;
				}
			}
		}catch (Exception e) {
			LOGGER.error("decrypt error, msg=[{}]", e.getMessage());
			json.setCode(0);
			json.setMessage("decrypt error");
		}*/
		return json;
	}

}
